<template>
  <div id="db" style="height: calc(100vh - 28px); width: 100%">
    <!--            -->
    <q-bar
      style="height: 28px"
      class="q-mx-xs rounded-borders bg-gradation-top-fdcbf1-e6dee9"
    >
      <span class="text-no-wrap q-mr-sm">
        {{ selected }}
      </span>
<!--      <q-btn-->
<!--        dense-->
<!--        size="sm"-->
<!--        icon-right="save"-->
<!--        class="bg-white text-red"-->
<!--        flat-->
<!--        @click="querySQL"-->
<!--      >-->
<!--        <q-tooltip> 保存 </q-tooltip>-->
<!--      </q-btn>-->
      <q-space />
      <q-btn
        dense
        size="sm"
        icon-right="play_arrow"
        class="bg-white text-red"
        flat
        @click="querySQL"
      >
        <q-tooltip> {{$t('run')}} </q-tooltip>
      </q-btn>
    </q-bar>
    <q-splitter v-model="splitterModel" style="height: calc(100% - 32px)">
      <template v-slot:before>
        <q-tree
          v-model:expanded="expanded"
          v-model:selected="selected"
          v-model:ticked="ticked"
          :nodes="dbTree"
          class="q-pl-md"
          default-expand-all
          dense
          no-connectors
          node-key="name"
          selected-color="purple"
          tick-strategy="leaf"
        >
          <template v-slot:default-header="prop">
            <div
              class="flex full-width no-wrap items-center justify-start"
              @contextmenu="clickDb(prop.node.label, prop.node.data)"
            >
              <q-icon
                :name="prop.node.icon || 'share'"
                class="q-mr-sm"
                color="orange"
                inertial
                size="16px"
              />
              {{ prop.node.label }}
            </div>
          </template>

          <template v-slot:default-body="prop">
            <span class="text-weight-bold">{{
              prop.node.tableName || prop.node.columnName
            }}</span>
          </template>
        </q-tree>
      </template>

      <template v-slot:after>
        <q-splitter v-model="sqlSplitterModel" horizontal style="height: 100%">
          <template v-slot:before>
            <ql-editor
              ref="sqlEditor"
              :content="sqlContent"
              editor-id="templateEditor"
              style="height: 100%; width: 100%"
              temp-type="sql"
            />
          </template>

          <template v-slot:after>
            <div id="table" style="height: 100%; width: 100%">
              <q-table
                v-model:pagination="pagination"
                :columns="columns"
                :rows="rows"
                :rows-per-page-options="[0]"
                :style="{ height: tableHeight + 'px' }"
                class="my-sticky-dynamic"
                dense
                flat
                row-key="name"
                separator="cell"
                virtual-scroll
              >
                <template v-slot:body="props">
                  <q-tr :props="props">
                    <q-td
                      v-for="item in props.cols"
                      :key="item.name"
                      :props="props"
                      class="bg-grey-3"
                    >
                      <!--                      <q-input dense borderless v-model="props.row[item.name]"/>-->

                      {{ props.row[item.name] }}
                      <q-popup-edit
                        v-slot="scope"
                        v-model="props.row[item.name]"
                        buttons
                        :title="item.name"
                      >
                        <q-input
                          outlined
                          v-model="scope.value"
                          autofocus
                          counter
                          dense
                        />
                      </q-popup-edit>
                    </q-td>
                  </q-tr>
                </template>
              </q-table>
            </div>
          </template>
        </q-splitter>
      </template>
    </q-splitter>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import QlEditor from 'components/QlEditor.vue';
import { showAllColumns, showTables, stmtDatabase } from 'src/api/DatabaseApi';

const splitterModel = ref(24);
const sqlSplitterModel = ref(60);
const dbHeight = ref(0);
const selected = ref(null);
const dbTreeList = ref({} as { tables: object });
const pagination = ref({
  rowsPerPage: 0,
});
const ticked = ref([]);
const expanded = ref([]);
const dbTree = ref([
  {
    label: 'xiu-life',
    name: 'xiu-life',
    icon: 'storage',
    children: [
      {
        name: 'tables',
        label: 'tables',
        data: 'tables',
        icon: 'folder',
        children: [],
      },
    ],
  },
]);
const sqlContent = ref('');
const clickDb = async (label: string, data: string) => {
  selected.value = label;
  let res = '';
  if (data === 'tables') {
    res = await window.ipcCom.dbMenu();
  } else if (data !== 'tables') {
    if (data.includes('.')) {
      res = await window.ipcCom.fieldMenu();
      if (res === 'copy') {
        await window.ipcCom.clipboard(label);
      }
    } else {
      res = await window.ipcCom.tableMenu();
      if (res === 'query') {
        sqlContent.value = `select * from ${data}`;
      }
      if (res === 'copy') {
        await window.ipcCom.clipboard(label);
      }
    }
  }
};
const initDbTree = async () => {
  await showTables().then(async (res) => {
    dbTreeList.value.tables = res;
    dbTreeList.value.tables.type = 'tables';

    const columnList = await showAllColumns();
    const fields = columnList?.fields as [];
    const results = columnList?.results as [];
    console.log(fields);
    console.log(results);

    res.results.forEach((item) => {
      console.log(item.TABLE_NAME);
      let temp = {};
      temp[item.TABLE_NAME] = {};
      dbTreeList.value = { ...dbTreeList.value, ...temp };
      console.log('dbTreeList.value', dbTreeList.value);
      dbTreeList.value[item.TABLE_NAME].results = results.filter((i) => {
        return i.TABLE_NAME === item.TABLE_NAME;
      });
      dbTreeList.value[item.TABLE_NAME].fields = fields;
      dbTreeList.value[item.TABLE_NAME].type = 'fields';
      dbTree.value[0].children[0].children.push({
        label: item.TABLE_NAME,
        icon: 'table_view',
        name: item.TABLE_NAME,
        tableName: item.TABLE_COMMENT,
        data: item.TABLE_NAME,
        type: 'tebles',
      });
    });
    dbTree.value[0].children[0].children.forEach((i) => {
      i.children = dbTreeList.value[i.label].results.map((j) => {
        return {
          label: j.COLUMN_NAME,
          icon: 'text_fields',
          name: i.label + '.' + j.COLUMN_NAME,
          columnName: j.COLUMN_COMMENT,
          data: i.label + '.' + j.COLUMN_NAME,
          type: 'fields',
        };
      });
    });
  });
};
watch(
  selected,
  async (newValue, oldValue) => {
    if (!newValue) selected.value = oldValue;
    if (!dbTreeList.value[newValue]?.fields) return;
    columns.value = [];
    rows.value = [];
    await stmtDatabase(`select * from ${selected.value}`).then((res) => {
      columns.value = [];
      rows.value = [];
      console.log(res);
      columns.value = res.fields.map((item) => {
        return {
          name: item.orgName,
          label: item.orgName,
          field: item.name,
          align: 'left',
          sortable: true,
        };
      });
      rows.value = res.results;
    });

    // dbTreeList.value[newValue].fields.forEach((item) => {
    //   columns.value.push({
    //     name: item.orgName,
    //     label: item.orgName,
    //     field: item.name,
    //     align: 'center',
    //     sortable: true,
    //   });
    // });
    // rows.value = dbTreeList.value[newValue].results;
  },
  { deep: true }
);
const columns = ref(
  [] as {
    name: string;
    label: string;
    align?: string;
    field: string;
    sortable: boolean;
  }[]
);
const querySQL = () => {
  stmtDatabase(sqlEditor.value?.getEditorContent()).then((res) => {
    columns.value = [];
    rows.value = [];
    res.fields.forEach((item) => {
      columns.value.push({
        name: item.orgName,
        label: item.orgName,
        field: item.name,
        align: 'left',
        sortable: true,
      });
    });
    rows.value = res.results;
  });
};
const sqlEditor = ref(null);
const rows = ref([]);
const tableHeight = ref(0);

onMounted(() => {
  let dbDiv = document.querySelector('#db') as HTMLDivElement;
  let tableDiv = document.querySelector('#table') as HTMLDivElement;
  dbHeight.value = dbDiv.scrollHeight;
  window.addEventListener('resize', () => {
    dbHeight.value = dbDiv.scrollHeight;
    console.log(dbDiv.scrollHeight);
    console.log(tableDiv.scrollHeight);
    console.log(
      dbHeight.value - 50 - (dbHeight.value * sqlSplitterModel.value) / 100
    );
  });
  const resizeObserver = new ResizeObserver((entries) => {
    for (let entry of entries) {
      const { width, height } = entry.contentRect;
      console.log(width, height);
      tableHeight.value = height;
    }
  });

  resizeObserver.observe(tableDiv);
  initDbTree();

  //
});
</script>
